package com.tusuo.stds.ui.password;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;

import com.andreabaccega.formedittextvalidator.SameValueValidator;
import com.andreabaccega.widget.FormEditText;
import com.tusuo.stds.R;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.util.Utils;
import com.tusuo.stds.util.validator.PasswordValidator;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.StringRes;

/**
 * Created by developer on 17-8-29.
 */

@EActivity(R.layout.activity_password)
public class PasswordActivity extends BaseToolbarActivity<PasswordView,PasswordPresenter> implements PasswordView {

    @StringRes(R.string.err_msg_password)
    String strErrMsgPassword;
    @StringRes(R.string.err_msg_confirm_password)
    String strErrMsgConfirmPassword;

    @ViewById(R.id.password_et_new_psw)
    FormEditText editNew;
    @ViewById(R.id.password_et_old_psw)
    FormEditText editOld;
    @ViewById(R.id.password_et_repeat_psw)
    FormEditText editRepeat;
    @ViewById(R.id.password_btn_finish)
    Button btnFinish;

    @ViewById(R.id.tv_msg)
    TextView tvMsg;

    @ColorRes(R.color.colorPrimary)
    int toolbarBgColor;
    @ColorRes(R.color.textColorPrimary)
    int toolbarTextColor;

    private PasswordPresenter mPresenter;
    private final int SHOW_SLOGAN_DELAY_CODE = 666;
    private final int RESET_PASSWORD_RESULT_CODE = 321;

    @NonNull
    @Override
    public PasswordPresenter createPresenter() {
        mPresenter = new PasswordPresenter();
        return mPresenter;
    }

    @AfterViews
    void initData() {
        setupUI(this,toolbarBgColor,toolbarTextColor);
        ToolbarOwner.Config config = new ToolbarOwner.Config("修改密码", true, R.drawable.ic_back_dark, null);
        mToolbarOwner.setConfig(config);

        editNew.addValidator(new PasswordValidator("格式不正确"));

        editRepeat.addValidator(new SameValueValidator(editNew,strErrMsgConfirmPassword));

        editNew.addTextChangedListener(new EditTextChangedListener());
        editOld.addTextChangedListener(new EditTextChangedListener());
        editRepeat.addTextChangedListener(new EditTextChangedListener());
    }

    @Click(R.id.password_btn_finish)
    void toNextAction() {
        // 强制隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        checkNewPassword();
    }

    /**
     * 顶部显示错误信息
     * @param errMsg
     */
    @Override
    public void showErrMsg(String errMsg) {
        tvMsg.setText(errMsg);
        tvMsg.setTextColor(Color.RED);
        handler.sendEmptyMessageDelayed(SHOW_SLOGAN_DELAY_CODE,3000);
    }

    /**
     * 错误信息显示3秒后 显示默认信息
     */
    public void showSlogan() {
        tvMsg.setText(getString(R.string.slogan));
        tvMsg.setTextColor(Color.WHITE);
    }

    /**
     * 检查新密码是否符合标准
     */
    void checkNewPassword() {
        if (editNew.testValidity()) {
            // 检查两次密码是否一致
            if (editRepeat.testValidity()) {
                presenter.commitPassword(editNew.getText().toString().trim(), editOld.getText().toString().trim());
            }else {
                showErrMsg(strErrMsgConfirmPassword);
            }
        } else {
            if (editNew.getText().length() >= 6 && editNew.getText().length() <= 30) {
                showErrMsg("密码不能含有特殊字符");
            }else {
                showErrMsg(strErrMsgPassword);
            }
        }
    }

    /**
     * 新密码提交成功 关闭页面并跳转到登录页面
     */
    @Override
    public void setOnActivityResult() {
        Utils.UI.showToastShort("密码修改成功，请您重新登录");
        setResult(RESET_PASSWORD_RESULT_CODE);
        finish();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == SHOW_SLOGAN_DELAY_CODE) {
                showSlogan();
            }
        }
    };

    private class EditTextChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (editNew.getText().length() > 0
                    && editOld.getText().length() > 0
                    && editRepeat.getText().length() > 0) {
                btnFinish.setBackgroundResource(R.drawable.selector_theme_button);
                btnFinish.setEnabled(true);
            } else {
                btnFinish.setBackgroundResource(R.drawable.shape_theme_button_disabled);
                btnFinish.setEnabled(false);
            }
        }
    }

}
